package com.dd.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dd.dto.DishDTO;
import com.dd.entity.Dish;
import com.dd.service.IDishService;
import com.dd.utils.FileUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 * 菜品表 前端控制器
 * </p>
 *
 * @author dhd
 * @since 2025-01-12 09:32
 */
@Slf4j
@Tag(name = "菜品管理")
@RestController
@RequestMapping("/dishes")
@RequiredArgsConstructor
@CrossOrigin
public class DishController {
    @Autowired
    private IDishService dishService;

    @Value("${upload.path}")
    private String uploadPath;

    @Operation(summary = "上传菜品图片")
    @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Map<String, String> uploadImage(@RequestParam("file") MultipartFile file) throws IOException {
        try {
            // 验证文件
            FileUtils.validateImageFile(file);

            // 获取项目根目录
            String userDir = System.getProperty("user.dir");
            Path fullPath = Paths.get(userDir + uploadPath+ "/images");
            File uploadDir = fullPath.toFile();

            // 检查上传目录是否存在，不存在则创建
            if (!uploadDir.exists()) {
                boolean created = uploadDir.mkdirs();
                if (!created) {
                    throw new IOException("无法创建上传目录");
                }
            }

            // 生成唯一的文件名
            String originalFilename = file.getOriginalFilename();
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String filename = UUID.randomUUID().toString() + extension;

            // 保存文件
            File destFile = new File(uploadDir, filename);
            file.transferTo(destFile);

            log.info("文件上传成功：{}", destFile.getAbsolutePath());

            // 返回文件访问路径
            Map<String, String> result = new HashMap<>();
            result.put("url", "/images/" + filename);
            return result;

        } catch (Exception e) {
            log.error("文件上传失败", e);
            throw e;
        }
    }

    @Operation(summary = "创建菜品")
    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public Dish create(@Valid @RequestBody DishDTO dishDTO) {
        return dishService.create(dishDTO);
    }

    @Operation(summary = "更新菜品")
    @PutMapping("/{id}")
    public Dish update(@PathVariable Long id, @Valid @RequestBody DishDTO dishDTO) {
        return dishService.update(id, dishDTO);
    }

    @Operation(summary = "删除菜品")
    @DeleteMapping("/{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void delete(@PathVariable Long id) {
        dishService.delete(id);
    }

    @Operation(summary = "获取菜品详情")
    @GetMapping("/{id}")
    public Dish getById(@PathVariable Long id) {
        return dishService.getById(id);
    }

    @Operation(summary = "分页获取菜品列表")
    @GetMapping
    public Page<Dish> list(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "5") int size,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) Long categoryId
    ) {
        return dishService.list(page, size, name, categoryId);
    }

    @Operation(summary = "更新菜品状态")
    @PatchMapping("/{id}/status")
    public void updateStatus(@PathVariable Long id, @RequestParam Byte status) {
        dishService.updateStatus(id, status);
    }
}
